let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
let Goods = require('../model/goods');//商品数据

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/imooc', {useMongoClient: true});//连接

mongoose.connection.on('connected', function () {
  console.log('连接成功');
});
mongoose.connection.on('error', function () {
  console.log('连接失败');
});

//查询商品
router.get('/list', function (req, res, next) {

  let paramsObj = req.query;                  //所有参数
  let page = parseInt(paramsObj.page);        //页数
  let pageSize = parseInt(paramsObj.pageSize);//页大小
  let skip = (page - 1) * pageSize;           //跳过几条
  let priceChecked = paramsObj.priceChecked;  //价格区间参数
  let priceGt,priceLt = 0;                    //价格区间
  let param = {};                             //接受参数
  if (priceChecked!='All'){
    switch (priceChecked) {
      case '0' : priceGt = 0; priceLt = 100;break;
      case '1' : priceGt = 100; priceLt = 500;break;
      case '2' : priceGt = 500; priceLt = 1000;break;
      case '3' : priceGt = 1000; priceLt = 5000;break;
    }
    param = {
      salePrice : {     //筛选价格
        $gt : priceGt,
        $lte : priceLt,
      }
    };
  }

  let goodsModel = Goods.find(param).skip(skip).limit(pageSize);
  goodsModel.exec(function (err, doc) {
    if (err) {
      res.json({
        status: 1,
        msg: err.message
      });
    } else {
      res.json({
        status: 0,
        msg: '',
        data: {
          count: doc.length,
          list: doc
        }
      });
    }
  });

});

//添加到购物车
let User = require('../model/users');
router.post('/addCart', function(req, res, next) {
  let userId = '100000077',productId = req.body.productId;
  //查找用户
  User.findOne({userId : userId},function (err1,userDoc) {
    if(err1){
      res.json({
        status:"1",
        msg:err1.message,
      });
      console.log(1);
    }else{
      //查询到了用户信息
      if(userDoc){
        let goodsItem = '';
        userDoc.cartList.forEach(item=>{
          if (item.productId == productId){
            goodsItem = item;
            item.productNum ++;
          }
        });
        if (goodsItem) {
          userDoc.save(function (err3,newDoc) {
            if (err3) {
              res.json({
                status:"1",
                msg:err3.message,
              });
              console.log(3);
            }else{
              res.json({ status : 0 ,msg : '加入成功',result : ''});
            }

          });
        }else{
          Goods.findOne({productId:productId},function (err2,proDoc) {
            if(err2){
              res.json({
                status:"1",
                msg:err2.message,
              });
              console.log(2);
            } else {
              if (proDoc) {
                proDoc.productNum = 1;
                proDoc.checked = true;
                userDoc.cartList.push(proDoc);
                userDoc.save(function (err3,newDoc) {
                  if (err3) {
                    res.json({
                      status:"1",
                      msg:err3.message,
                    });
                    console.log(3);
                  }else{
                    res.json({ status : 0 ,msg : '加入成功',result : ''});
                  }
                });
              }
            }
          })
        }
      }
    }
  })
});



module.exports = router;
